// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var compressing = require('compressing');
var shell = require('shelljs');
var fs = require('fs');
var path = require('path');

var curPath = __dirname;
var jsonObj = {};
try {
    jsonObj = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json')));
} catch (error) {
    console.error(error); // eslint-disable-line 	no-console
}

var version = jsonObj.version || '1.0.0';
var appName = jsonObj.name || 'CloudAppSdk_H5';

function npmInstallWebapp() {
    shell.cd(curPath);
    if (shell.exec('npm install').code !== 0) {
        shell.echo('npm install webapp fail');
        shell.exit(1);
    }

    shell.echo('npm install webapp success');
} 

function npmPackageWebapp() {
    shell.cd(curPath);
    if (shell.exec('npm run build').code !== 0) {
        shell.echo('npm package build fail');
        shell.exit(1);
    }

    shell.echo('npm package build success');
}

function buildPackage() {
    var pkgName = appName + '_Release_' + version;
    var dist = path.join(__dirname, 'dist');
    var tarPkg = path.join(__dirname, 'dist', 'CloudAppSdk.tar');
    var tgzPkg = path.join(__dirname, 'dist', pkgName + '.tar.gz');
    var innerDir = path.join(__dirname, pkgName);
    shell.rm('-r', innerDir);
    shell.mkdir('-p', innerDir);
    shell.cp('-r', dist + '/*', innerDir);

    compressing.tar.compressDir(innerDir, tarPkg)
        .then(function () {
            console.log('package tar success.'); // eslint-disable-line 	no-console
            return compressing.gzip.compressFile(tarPkg, tgzPkg);
        })
        .then(function () {
            console.log('package gtar success.'); // eslint-disable-line 	no-console
            shell.rm('-r', innerDir);
        })
        .catch(function (err) {
            console.log('package error: ', err); // eslint-disable-line 	no-console
        });
}

npmInstallWebapp();
npmPackageWebapp();
buildPackage();
